import tkinter as tk
from tkinter import scrolledtext
import pyautogui
import threading
import time
import os

 
class ScreenMonitorApp:
    def __init__(self, root):
        self.root  = root
        self.root.title("百炼自动点击器")
        self.root.geometry("350x380") 
        self.root.resizable(False,  False)

        # 状态变量
        self.running  = False
        self.monitor_thread  = None

        # 图像路径（可修改）
        self.go_path  = "go.png" 
        self.cancel_path  = "cancel.png" 
        self.yellow_path  = "yellow.png" 
        self.red_path  = "red.png" 
        self.max_path  = "max.png" 
        self.box_path  = "box.png"
        self.ok_path  = "ok.png"

        # GUI 元素
        self.title_label  = tk.Label(root, text="百炼英雄监控工具", font=("Arial", 16))
        self.title_label.pack(pady=10) 

        self.status_label  = tk.Label(root, text="状态：未运行", fg="gray")
        self.status_label.pack(pady=5) 

        self.btn_frame  = tk.Frame(root)
        self.btn_frame.pack(pady=20) 

        self.zm_btn  = tk.Button(self.btn_frame,  text="招募监控", width=10, height=2, bg="green", fg="white", command=self.zm_monitoring) 
        self.zm_btn.grid(row=0,  column=0, padx=10)

        self.box_btn  = tk.Button(self.btn_frame,  text="宝箱监控", width=10, height=2, bg="green", fg="white", command=self.box_monitoring) 
        self.box_btn.grid(row=0,  column=1, padx=10)

        self.stop_btn  = tk.Button(self.btn_frame,  text="停止监控", width=10, height=2, bg="red", fg="white", command=self.stop_monitoring,  state=tk.DISABLED)
        self.stop_btn.grid(row=0,  column=2, padx=10)

        self.text  = scrolledtext.ScrolledText(root,  font=("Arial", 9))
        self.text.pack(padx=10,pady=5) 


    def click(self, s, location):
            center_x, center_y = pyautogui.center(location) 
            pyautogui.click(center_x,  center_y)
            self.text.insert(tk.END, f"✅ 已点击{s}：位置 ({center_x}, {center_y})\n")
            self.text.yview(tk.END)

    def zm_image(self):
        """查找并点击图像"""
        # 多尺度匹配，提高识别成功率
        max = False
        try:
            location = pyautogui.locateOnScreen(self.cancel_path, confidence=0.75)
        except Exception as e:
            try:
                location = pyautogui.locateOnScreen(self.red_path, confidence=0.75, grayscale=False)
                if location:
                    max = True
            except Exception as e:
                try:
                    location = pyautogui.locateOnScreen(self.yellow_path, confidence=0.75, grayscale=False)
                    if location:
                        max = True
                except Exception as e:
                    pass
            if max:
                try:
                    location = pyautogui.locateOnScreen(self.max_path, confidence=0.8)
                except Exception as e:
                    location = None
                else:
                    self.click('最大倍数', location)
            try:
                location = pyautogui.locateOnScreen(self.go_path, confidence=0.8)
            except Exception as e:
                location = None
            else:
                self.click('招募', location)
        else:
            self.click('放弃', location)

    def box_image(self):
        """查找并点击图像"""
        # 多尺度匹配，提高识别成功率
        max = False
        try:
            location = pyautogui.locateOnScreen(self.box_path, confidence=0.75, grayscale=False)
        except Exception as e:
            pass
        else:
            self.click('宝箱', location)
        try:
            location = pyautogui.locateOnScreen(self.ok_path, confidence=0.8)
        except Exception as e:
            pass
        else:
            self.click('确定', location)
            time.sleep(0.5)
            self.click('关闭', location)

    def zm_loop(self):
        """监控主循环"""
        while self.running: 
            self.zm_image()
            time.sleep(1.5)   # 每30秒检测一次

    def box_loop(self):
        """监控主循环"""
        while self.running: 
            self.box_image()
            time.sleep(0.5)   # 每30秒检测一次

    def zm_monitoring(self):
        """启动监控线程"""
        if not self.running: 
            self.running  = True
            self.update_status(" 招募运行", "green")
            self.zm_btn.config(state=tk.DISABLED) 
            self.box_btn.config(state=tk.DISABLED) 
            self.stop_btn.config(state=tk.NORMAL) 

            # 启动后台线程防止阻塞 GUI
            self.monitor_thread  = threading.Thread(target=self.zm_loop,  daemon=True)
            self.monitor_thread.start() 

    def box_monitoring(self):
        """启动监控线程"""
        if not self.running: 
            self.running  = True
            self.update_status(" 宝箱运行", "green")
            self.zm_btn.config(state=tk.DISABLED) 
            self.box_btn.config(state=tk.DISABLED) 
            self.stop_btn.config(state=tk.NORMAL) 

            # 启动后台线程防止阻塞 GUI
            self.monitor_thread  = threading.Thread(target=self.box_loop,  daemon=True)
            self.monitor_thread.start() 

    def stop_monitoring(self):
        """停止监控"""
        self.running  = False
        self.update_status(" 已停止", "red")
        self.zm_btn.config(state=tk.NORMAL) 
        self.box_btn.config(state=tk.NORMAL) 
        self.stop_btn.config(state=tk.DISABLED) 

    def update_status(self, text, color):
        """更新状态标签"""
        self.status_label.config(text=f" 状态：{text}", fg=color)


# 主程序入口
if __name__ == "__main__":
    root = tk.Tk()
    app = ScreenMonitorApp(root)
    root.mainloop()